package com.geekstudy;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 演示 RequestDispatcher 的 include 和 forward
 */
@WebServlet(urlPatterns = "/demoRequestDispatcher", asyncSupported = false)
public class DemoRequestDispatcher extends HttpServlet {

    @Override
    public void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
        System.out.println(DemoRequestDispatcher.class.getName() + " 开始");

        String requestType = httpRequest.getParameter("requestType");

        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setHeader("content-type","text/html;charset=UTF-8");

        if(requestType == null || requestType.isEmpty()) {
            String message = "requestType is " + requestType + ". 仅展示默认页面";
            outMessage(httpResponse, message);
        } else if(requestType.startsWith("i")) {
            httpRequest.getRequestDispatcher("welcome.jsp?from=DemoRequestDispatcher&customerRequestDispatcher=include&requestType" + requestType).include(httpRequest, httpResponse);
        } else if(requestType.startsWith("f")) {
            httpRequest.getRequestDispatcher("welcome.jsp?from=DemoRequestDispatcher&customerRequestDispatcher=forward&requestType" + requestType).forward(httpRequest, httpResponse);
        } else {
            String message = "不支持的请求类型:" + requestType;
            outMessage(httpResponse, message);
        }

        System.out.println(DemoRequestDispatcher.class.getName() + "完成");
    }

    private void outMessage(HttpServletResponse httpResponse, String message) throws ServletException, IOException{

        httpResponse.getOutputStream().write(message.getBytes("UTF-8"));
    }
}
